package com.factory.aiclient.config;

import com.alibaba.fastjson.JSONObject;
import com.factory.aiclient.service.UserDeviceService;
import com.factory.aiclient.util.SpringCtxUtils;
import com.factory.common.bean.UserDevices;
import com.factory.common.constant.DeviceConstant;
import com.factory.common.constant.ResultCode;
import com.factory.common.constant.UserConstant;
import com.factory.common.core.LoginException;
import com.factory.common.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 客户端访问安全拦截器
 */
@Configuration
@Slf4j
public class ClientInterceptor implements WebMvcConfigurer, HandlerInterceptor {

    private UserDeviceService userDeviceService = SpringCtxUtils.getBean(UserDeviceService.class);

    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new ClientInterceptor()).addPathPatterns("/**")
                .excludePathPatterns("/aiclient/index/**")
                .excludePathPatterns("/aiclient/ws/**")
                .excludePathPatterns("/aiclient/carwash/**")
                .excludePathPatterns("/video/**");
    }


    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String serialNO = request.getHeader(DeviceConstant.SERIALNO);

        if (StringUtil.isEmpty(serialNO)) {
            log.warn("无权限设备访问,{}",request.getRequestURL());
            throw new LoginException(ResultCode.NoAuth.code, ResultCode.NoAuth.message);
        }

        UserDevices current = userDeviceService.getCurrent(serialNO);
        if(null == current){
            log.warn("设备不存在!");
            throw new LoginException(ResultCode.InvalidDevice.code, ResultCode.InvalidDevice.message);
        }

        request.setAttribute(UserDeviceService.CurrentDevice,current);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        request.removeAttribute(UserDeviceService.CurrentDevice);
    }
}
